package com.fengye.serialization.serializer.impl;

import com.fengye.serialization.serializer.Serializer;

import java.io.*;

/**
 * 基于java的序列化
 *
 * @Author fengye
 * @Date 2023/2/12 12:13
 **/
public class DefaultJavaSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T obj) throws Exception{
        if(obj ==  null) {
            return new byte[0];
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        objectOutputStream.close();

        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();

        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception{

        if(data == null) {
            return null;
        }

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        T obj = (T)objectInputStream.readObject();

        objectInputStream.close();
        byteArrayInputStream.close();
        return obj;
    }
}
